<template>
  <div class="logs">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.path"
            placeholder="搜索请求路径"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.method" placeholder="HTTP方法" clearable>
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.statusCode" placeholder="状态码" clearable>
            <el-option label="200" value="200" />
            <el-option label="400" value="400" />
            <el-option label="404" value="404" />
            <el-option label="500" value="500" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
      <el-row style="margin-top: 15px">
        <el-col :span="24" style="text-align: right">
          <el-button type="warning" @click="handleCleanLogs">清理日志</el-button>
          <el-button type="danger" @click="handleExportLogs">导出日志</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 日志列表 -->
    <el-card class="table-card">
      <el-table :data="logs" style="width: 100%" v-loading="loading">
        <el-table-column prop="createdAt" label="时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="requestMethod" label="方法" width="80">
          <template #default="scope">
            <el-tag :type="getMethodTagType(scope.row.requestMethod)" size="small">
              {{ scope.row.requestMethod }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="requestPath" label="路径" min-width="200" show-overflow-tooltip />
        <el-table-column prop="responseStatus" label="状态码" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.responseStatus)" size="small">
              {{ scope.row.responseStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="responseTimeMs" label="响应时间" width="120">
          <template #default="scope">
            {{ scope.row.responseTimeMs }}ms
          </template>
        </el-table-column>
        <el-table-column prop="ipAddress" label="IP地址" width="120" />
        <el-table-column prop="userAgent" label="User Agent" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="日志详情"
      width="80%"
      top="5vh"
    >
      <div class="log-detail" v-if="currentLog">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="请求时间">
            {{ formatTime(currentLog.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="响应时间">
            {{ currentLog.responseTimeMs }}ms
          </el-descriptions-item>
          <el-descriptions-item label="HTTP方法">
            <el-tag :type="getMethodTagType(currentLog.requestMethod)" size="small">
              {{ currentLog.requestMethod }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态码">
            <el-tag :type="getStatusTagType(currentLog.responseStatus)" size="small">
              {{ currentLog.responseStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="请求路径">
            {{ currentLog.requestPath }}
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ currentLog.ipAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="User Agent" :span="2">
            {{ currentLog.userAgent }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <h4>请求头</h4>
          <div class="json-viewer">
            <pre>{{ formatJson(currentLog.requestHeaders) }}</pre>
          </div>
        </div>

        <div class="detail-section">
          <h4>请求参数</h4>
          <div class="json-viewer">
            <pre>{{ formatJson(currentLog.requestParams) }}</pre>
          </div>
        </div>

        <div class="detail-section">
          <h4>请求体</h4>
          <div class="json-viewer">
            <pre>{{ formatJson(currentLog.requestBody) }}</pre>
          </div>
        </div>

        <div class="detail-section">
          <h4>响应头</h4>
          <div class="json-viewer">
            <pre>{{ formatJson(currentLog.responseHeaders) }}</pre>
          </div>
        </div>

        <div class="detail-section">
          <h4>响应体</h4>
          <div class="json-viewer">
            <pre>{{ formatJson(currentLog.responseBody) }}</pre>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 清理日志对话框 -->
    <el-dialog
      v-model="cleanDialogVisible"
      title="清理日志"
      width="400px"
    >
      <el-form :model="cleanForm" label-width="100px">
        <el-form-item label="清理条件">
          <el-radio-group v-model="cleanForm.type">
            <el-radio label="days">按天数清理</el-radio>
            <el-radio label="all">清理全部</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="天数" v-if="cleanForm.type === 'days'">
          <el-input-number
            v-model="cleanForm.days"
            :min="1"
            :max="365"
            placeholder="请输入天数"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cleanDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmCleanLogs" :loading="cleaning">确定清理</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { logApi } from '@/api'

export default {
  name: 'Logs',
  setup() {
    const loading = ref(false)
    const cleaning = ref(false)
    const detailVisible = ref(false)
    const cleanDialogVisible = ref(false)
    const logs = ref([])
    const currentLog = ref(null)

    // 搜索表单
    const searchForm = reactive({
      path: '',
      method: '',
      statusCode: '',
      timeRange: []
    })

    // 分页信息
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 清理表单
    const cleanForm = reactive({
      type: 'days',
      days: 7
    })

    // 获取日志列表
    const fetchLogs = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          size: pagination.size,
          requestPath: searchForm.path,
          requestMethod: searchForm.method,
          responseStatus: searchForm.statusCode
        }

        // 添加时间范围参数
        if (searchForm.timeRange && searchForm.timeRange.length === 2) {
          params.startTime = searchForm.timeRange[0]
          params.endTime = searchForm.timeRange[1]
        }

        const response = await logApi.getLogs(params)
        if (response.code === 0) {
          logs.value = response.data.records || []
          pagination.total = response.data.total || 0
        } else {
          ElMessage.error(response.message || '加载日志列表失败')
        }
      } catch (error) {
        ElMessage.error('加载日志列表失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      fetchLogs()
    }

    // 重置搜索
    const handleReset = () => {
      Object.assign(searchForm, {
        path: '',
        method: '',
        statusCode: '',
        timeRange: []
      })
      pagination.page = 1
      fetchLogs()
    }

    // 查看详情
    const handleViewDetail = (row) => {
      currentLog.value = row
      detailVisible.value = true
    }

    // 清理日志
    const handleCleanLogs = () => {
      cleanDialogVisible.value = true
    }

    // 确认清理日志
    const confirmCleanLogs = async () => {
      try {
        cleaning.value = true
        
        if (cleanForm.type === 'days') {
          const response = await logApi.cleanLogs(cleanForm.days)
          if (response.code === 0) {
            ElMessage.success(`已清理${cleanForm.days}天前的日志`)
          } else {
            ElMessage.error(response.message || '清理日志失败')
          }
        } else {
          const response = await logApi.cleanLogs(0) // 0表示清理全部
          if (response.code === 0) {
            ElMessage.success('已清理全部日志')
          } else {
            ElMessage.error(response.message || '清理日志失败')
          }
        }
        
        cleanDialogVisible.value = false
        fetchLogs()
      } catch (error) {
        console.error('清理日志失败:', error)
      } finally {
        cleaning.value = false
      }
    }

    // 导出日志
    const handleExportLogs = () => {
      ElMessage.info('导出功能开发中...')
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.page = 1
      fetchLogs()
    }

    const handleCurrentChange = (page) => {
      pagination.page = page
      fetchLogs()
    }

    // 获取方法标签类型
    const getMethodTagType = (method) => {
      const typeMap = {
        GET: 'success',
        POST: 'primary',
        PUT: 'warning',
        DELETE: 'danger'
      }
      return typeMap[method] || 'info'
    }

    // 获取状态码标签类型
    const getStatusTagType = (statusCode) => {
      if (statusCode >= 200 && statusCode < 300) return 'success'
      if (statusCode >= 400 && statusCode < 500) return 'warning'
      if (statusCode >= 500) return 'danger'
      return 'info'
    }

    // 格式化时间
    const formatTime = (timestamp) => {
      if (!timestamp) return ''
      return new Date(timestamp).toLocaleString('zh-CN')
    }

    // 格式化JSON
    const formatJson = (json) => {
      if (!json) return '无数据'
      try {
        if (typeof json === 'string') {
          return JSON.stringify(JSON.parse(json), null, 2)
        }
        return JSON.stringify(json, null, 2)
      } catch (error) {
        return json
      }
    }

    onMounted(() => {
      fetchLogs()
    })

    return {
      loading,
      cleaning,
      detailVisible,
      cleanDialogVisible,
      logs,
      currentLog,
      searchForm,
      pagination,
      cleanForm,
      handleSearch,
      handleReset,
      handleViewDetail,
      handleCleanLogs,
      confirmCleanLogs,
      handleExportLogs,
      handleSizeChange,
      handleCurrentChange,
      getMethodTagType,
      getStatusTagType,
      formatTime,
      formatJson
    }
  }
}
</script>

<style scoped>
.logs {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.log-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
}

.json-viewer {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.json-viewer pre {
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 